﻿using System;
using System.Linq;
using XRM.Security.DataAccess.Enums;
using XRM.Security.DataAccess.Repositories.Impl;
using XRM.Security.WebUI.Helpers;

namespace XRM.Security.WebUI.Models.Report.ReportBuilder
{
    public class UserReportBuilder : ReportBuilderBase
    {
        public override string TemplateFileName
        {
            get { return "Пользователи АИС"; }
        }

        private readonly UserRegisterRepository _userRegisterRepository;
        public UserReportBuilder(UserRegisterRepository userRegisterRepository)
        {
            _userRegisterRepository = userRegisterRepository;
        }

        public override string Create(CreateReportModel model)
        {
            var statuses = model.GetSelectedCheckBoxValues().ToList();
            var query = _userRegisterRepository.GetAll( s => statuses.Contains( s.Status ) )
                .SelectMany(s => s.InfoSystems).Where(s => s.RevokeDate == null)
                    .Select(s => new {s.InfoSystemId, s.InfoSystem.InfoSystemName, s.UserRegister.FirstName,
                    s.UserRegister.LastName, s.UserRegister.MotherName, s.UserRegister.Status});
            if (model.Value.HasValue)
            {
                query = query.Where( s => s.InfoSystemId == model.Value );
            }
            var users = query.OrderBy(s => s.InfoSystemName).ThenBy(s => s.LastName).AsEnumerable().Select( s => new UsersReportTypeUsers
                {
                    FirstName = s.FirstName,
                    MiddleName = s.MotherName,
                    SecondName = s.LastName,
                    System = s.InfoSystemName,
                    Status = ToUserReportUserStatus( (UserStatus)s.Status )
                } ).ToArray();
            var report = new UsersReportType
                {
                    CreateDate = DateTime.Now,
                    Users = users
                };
            return CreateXlsxDocument( Utils.SerializeToString(report) );
        }

        private static UsersReportTypeUsersStatus ToUserReportUserStatus(UserStatus status)
        {
            switch(status)
            {
                case UserStatus.NotWork:
                    return UsersReportTypeUsersStatus.Уволен;
                case UserStatus.Work:
                    return UsersReportTypeUsersStatus.Работающий;
                case UserStatus.Vacation:
                    return UsersReportTypeUsersStatus.Вдлительномотпуске;
            }
            throw new NotSupportedException(status.ToString());
        }
    }
}